package com.yao.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yao.mall.common.ErrorCode;
import com.yao.mall.common.UserHolder;
import com.yao.mall.config.BusinessException;
import com.yao.mall.constant.UserConstant;
import com.yao.mall.mapper.UserMapper;
import com.yao.mall.model.dto.AddressRequest;
import com.yao.mall.model.entity.Address;
import com.yao.mall.model.vo.AddressVO;
import com.yao.mall.model.vo.UserVO;
import com.yao.mall.service.AddressService;
import com.yao.mall.mapper.AddressMapper;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jiahua.yao
 * @description 针对表【address】的数据库操作Service实现
 * @date 2024-03-04 13:51:57
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address>
        implements AddressService {

    @Resource
    private AddressMapper addressMapper;

    @Override
    public List<AddressVO> getAddress() {
        UserVO user = UserHolder.getUser();
        if (user == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "请先登录");
        }
        Long userId = user.getId();
        QueryWrapper<Address> addressQueryWrapper = new QueryWrapper<>();
        addressQueryWrapper.eq("user_id", userId);
        List<Address> addresses = addressMapper.selectList(addressQueryWrapper);
        List<AddressVO> addressVOList = addresses.stream().map(address -> {
            AddressVO addressVO = new AddressVO();
            BeanUtils.copyProperties(address, addressVO);
            return addressVO;
        }).collect(Collectors.toList());
        return addressVOList;
    }

    @Override
    public Boolean addAddress(AddressRequest addressRequest) {
        //1、数据校验
        dateCheck(addressRequest);
        //1.1 获得该用户已有的地址数量
        UserVO user = UserHolder.getUser();
        QueryWrapper<Address> addressQueryWrapper = new QueryWrapper<>();
        addressQueryWrapper.eq("user_id", user.getId());
        Long count = addressMapper.selectCount(addressQueryWrapper);
        if (count >= UserConstant.MAX_COUNT) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "收货地址已超过最大上限");
        }
        //2、地址添加
        //2.1、是否设置为默认
        Address address = new Address();
        BeanUtils.copyProperties(addressRequest, address);
        if (count == 0) {
            //没有地址默认设置为1，即默认
            address.setIsDefault(1);
        }
        //merge
        if (addressRequest.getIsDefault() == 1 && count > 0) {
            //修改原先的默认地址
            this.changeDefault(user);
        }
        address.setUserId(user.getId());
        return this.save(address);
    }

    private static void dateCheck(AddressRequest addressRequest) {
        String provinceCode = addressRequest.getProvinceCode();
        String cityCode = addressRequest.getCityCode();
        String districtCode = addressRequest.getDistrictCode();
        String receiver = addressRequest.getReceiver();
        String contact = addressRequest.getContact();
        String detailAddress = addressRequest.getDetailAddress();
        if (StringUtils.isAnyBlank(provinceCode, cityCode, districtCode, receiver, contact, detailAddress)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "必填字段为空！");
        }
    }

    @Override
    public AddressVO updateAddress(AddressRequest addressRequest) {
        dateCheck(addressRequest);
        Address address = new Address();
        BeanUtils.copyProperties(addressRequest, address);
        boolean update = this.updateById(address);
        if (!update) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "更新失败！");
        }
        AddressVO addressVO = new AddressVO();
        BeanUtils.copyProperties(addressRequest, addressVO);
        return addressVO;
    }

    @Override
    public Boolean deleteAddress(Long id) {
        if (UserHolder.getUser() == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "身份校验失败，请确保已登录！");
        }
        if(addressMapper.selectById(id).getIsDefault() == 1){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "默认地址不可直接删除，请更换默认地址后删除！");
        }
        return this.removeById(id);
    }

    @Override
    public Boolean changeDefaultAddress(Long id) {
        UserVO user = UserHolder.getUser();
        //1.原先默认的地址修改为非默认
        changeDefault(user);
        //2.设置新的默认地址
        Address address = new Address();
        address.setId(id);
        address.setIsDefault(1);
        int i = addressMapper.updateById(address);
        return i > 0;
    }

    /**
     * 修改原先默认地址为非默认
     * @param user 用户vo
     */
    private void changeDefault(UserVO user) {
        QueryWrapper<Address> addressQueryWrapper = new QueryWrapper<>();
        addressQueryWrapper.eq("user_id", user.getId()).eq("is_default", 1);
        Address addressOld = new Address();
        addressOld.setIsDefault(0);
        int updateOld = addressMapper.update(addressOld, addressQueryWrapper);
        if (updateOld <= 0) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "原默认地址更新失败");
        }
    }
}




